package com.idp.system.excel;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.idp.common.constants.SystemParam;
import com.idp.system.entity.SysUserEntity;
import com.idp.system.entity.SysUserRoleEntity;
import com.idp.system.mapper.SysUserMapper;
import com.idp.system.mapper.SysUserRoleMapper;

import java.util.List;
import java.util.Map;

public class SysUserImportListener implements ReadListener<SysUserExcelDto> {

    private static final int BATCH_COUNT = 100;

    private List<SysUserExcelDto> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private SysUserMapper sysUserMapper;
    private SystemParam systemParam;
    private Map<String, String> roleMap;
    private SysUserRoleMapper sysUserRoleMapper;

    public SysUserImportListener(SysUserMapper sysUserMapper, SystemParam systemParam, Map<String, String> roleMap, SysUserRoleMapper sysUserRoleMapper) {
        this.sysUserMapper = sysUserMapper;
        this.systemParam = systemParam;
        this.roleMap = roleMap;
        this.sysUserRoleMapper = sysUserRoleMapper;
    }


    @Override
    public void invoke(SysUserExcelDto sysUserExcelDto, AnalysisContext analysisContext) {
        cachedDataList.add(sysUserExcelDto);
        if (cachedDataList.size() >= BATCH_COUNT) {
            this.saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        this.saveData();
    }

    private void saveData() {

        if(CollectionUtil.isNotEmpty(cachedDataList)) {
            for(SysUserExcelDto sysUserExcelDto : cachedDataList) {

                SysUserEntity sysUser = BeanUtil.toBean(sysUserExcelDto, SysUserEntity.class);
                sysUser.setId(IdUtil.simpleUUID());
                sysUser.setPwd(systemParam.getUserDefaultPwd());
                sysUserMapper.insert(sysUser);

                if(StrUtil.isNotEmpty(sysUserExcelDto.getRoleNames())) {
                    String[] roleNames = sysUserExcelDto.getRoleNames().split(",");
                    for(String roleName : roleNames) {
                        if(roleMap.containsKey(roleName)) {
                            SysUserRoleEntity userRole = new SysUserRoleEntity();
                            userRole.setId(IdUtil.simpleUUID());
                            userRole.setUserId(sysUser.getId());
                            userRole.setRoleId(roleMap.get(roleName));
                            sysUserRoleMapper.insert(userRole);
                        }
                    }
                }
            }
        }
    }
}
